document.addEventListener('DOMContentLoaded', () => {
    // 示例数据
    const projects = ['10米气步枪', '项目2', '项目3'];
    const coaches = {
        '10米气步枪': ['男子', '女子'],
        '项目2': ['教练C', '教练D'],
        '项目3': ['教练E', '教练F']
    };
    const names = {
        '男子': ['杨皓然', '于浩','苏文熙','刘禹岐','惠子程','田珈铭','王靖晖','杜林澍','高昊峥'],
        '女子': ['王一荻', '高莹','焦若璇','杜贝','张嘉轩','李佳静 '],
        '教练C': ['刘强', '陈静'],
        '教练D': ['杨涛', '朱红'],
        '教练E': ['孙丽', '周杰'],
        '教练F': ['吴刚', '周婷']
    };

    // 获取页面元素
    const projectSelect = document.getElementById('projects');
    const coachSelect = document.getElementById('coaches');
    const nameList = document.getElementById('names');
    const selectedNames = document.getElementById('selected-names');
    const generateButton = document.getElementById('generate-button');
    const chartArea = document.getElementById('chart');
    const statsMethodSelect = document.getElementById('stats-method');  

    // 初始化项目下拉框
    projects.forEach(project => {
        let option = document.createElement('option');
        option.value = project;
        option.textContent = project;
        projectSelect.appendChild(option);
    });

    // 存储已选择的姓名，跨多个教练
    let selectedNamesSet = new Set();

    // 处理项目下拉框的变化
    projectSelect.addEventListener('change', () => {
        const selectedProject = projectSelect.value;
        const coachesOptions = coaches[selectedProject] || [];

        // 更新教练下拉框
        coachSelect.innerHTML = '';
        coachesOptions.forEach(coach => {
            let option = document.createElement('option');
            option.value = coach;
            option.textContent = coach;
            coachSelect.appendChild(option);
        });
        coachSelect.dispatchEvent(new Event('change'));
    });

    // 处理教练下拉框的变化
    coachSelect.addEventListener('change', () => {
        const selectedCoach = coachSelect.value;
        const namesList = names[selectedCoach] || [];

        // 更新姓名列表，不清除现有选择
        nameList.innerHTML = '';
        namesList.forEach(name => {
            let li = document.createElement('li');
            li.textContent = name;

            // 如果该姓名已被选择，添加选中样式
            if (selectedNamesSet.has(name)) {
                li.classList.add('selected');
            }

            li.addEventListener('click', () => {
                if (li.classList.contains('selected')) {
                    li.classList.remove('selected');
                    selectedNamesSet.delete(name);  // 从集合中移除
                } else {
                    li.classList.add('selected');
                    selectedNamesSet.add(name);  // 添加到集合
                }
                updateSelectedNames();
            });
            nameList.appendChild(li);
        });
    });

    // 更新选择的姓名显示
    function updateSelectedNames() {
        selectedNames.innerHTML = '';
        selectedNamesSet.forEach(name => {
            let li = document.createElement('li');
            li.textContent = name;
            selectedNames.appendChild(li);
        });
    }

    generateButton.addEventListener('click', async () => {
        const selectedNamesList = Array.from(selectedNamesSet);
        const startDate = document.getElementById('start-date').value;
        const endDate = document.getElementById('end-date').value;
        const statsMethod = statsMethodSelect.value;
    
        // 验证所有必填字段是否填写完整
        if (selectedNamesList.length === 0 || !startDate || !endDate) {
            alert('请填写所有必填字段');
            return;
        }
    
        // 准备发送给服务器的数据，符合后端要求的格式
        const requestData = {
            nameList: selectedNamesList,
            startTime: startDate,
            endTime: endDate
        };
    
        try {
            // 发送请求到后端
            const response = await fetch('http://172.16.1.197:8080/athleteScore/drawBoxplot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQyYjBhYzAzLTk0ODUtNGFhYS04OGZjLWZhY2JmYjAxMTYyZCJ9.13Sz2K5HLIH4cRNH2G8WY1W5kzexIf844ChXP0nflHWKS1oZ3tAnjV-201tXUC6lG2UuWA-6X7joEoXFcc5fYg'
                },
                body: JSON.stringify(requestData)
            });
    
            // 检查响应是否正常
            if (!response.ok) {
                throw new Error('网络响应不正确');
            }
    
            // 解析 JSON 响应
            const responseData = await response.json();
    
            // 清除现有图表
            chartArea.innerHTML = '';
    
            // 检查响应数据是否包含成绩
            if (responseData.data) {
                // 根据选择的人数调用不同的渲染函数
                if (selectedNamesList.length === 1) {
                    renderChart(responseData.data[0], statsMethod);
                } else {
                    renderComparisonChart(responseData.data, statsMethod);
                }
            } else {
                alert('未找到数据');
            }
    
        } catch (error) {
            console.error('请求失败:', error);
            alert('请求失败，请检查控制台以获取详细信息');
        }
    });
    
    function calculateBoxPlotData(scores) {
        // 排序分数数组
        scores.sort((a, b) => a - b);
    
        const min = scores[0];
        const max = scores[scores.length - 1];
        const median = getPercentile(scores, 50);
        const q1 = getPercentile(scores, 25);
        const q3 = getPercentile(scores, 75);
    
        return [min, q1, median, q3, max];
    }
    
    // 用于计算百分位数的辅助函数
    function getPercentile(arr, percentile) {
        const index = (percentile / 100) * (arr.length - 1);
        const lower = Math.floor(index);
        const upper = Math.ceil(index);
        const weight = index - lower;
    
        if (upper >= arr.length) {
            return arr[lower];
        }
    
        return arr[lower] * (1 - weight) + arr[upper] * weight;
    }
    

    function formatTime(datetime, statsMethod) {
        const date = new Date(datetime);
        if (statsMethod === '周') {
            // 获取当前日期所在的周的开始和结束日期
            const startOfWeek = new Date(date.setDate(date.getDate() - date.getDay() + 1)); // 设定周一为一周的开始
            const endOfWeek = new Date(date.setDate(date.getDate() - date.getDay() + 7)); // 设定周日为一周的结束
            return `${startOfWeek.getFullYear()}.${startOfWeek.getMonth() + 1}.${startOfWeek.getDate()}.-${endOfWeek.getFullYear()}.${endOfWeek.getMonth() + 1}.${endOfWeek.getDate()}`;
        } else {
            return date.toLocaleDateString();
        }
    }

    function renderChart(data, statsMethod) {
        // 清空图表区域并设置样式
        chartArea.innerHTML = '';
        chartArea.style.display = 'flex';  // 使用flex布局
    
        // 创建图表容器
        const chartContainer = document.createElement('div');
        chartContainer.className = 'chart-container';
        chartArea.appendChild(chartContainer);
    
        const { name, athleteScores } = data;
        const boxPlotData = [];
        const averageData = [];
        const allScores = [];  // 用于计算全局平均值
        const weeklyData = {};
        let allQ1s = [];
    
        athleteScores.forEach(score => {
            const time = formatTime(score.datetime, statsMethod);
            if (!weeklyData[time]) {
                weeklyData[time] = [];
            }
            weeklyData[time].push(...score.socreList);
            allScores.push(...score.socreList);  // 收集所有得分
        });
    
        // 计算全局平均值
        const globalAverage = allScores.reduce((acc, val) => acc + val, 0) / allScores.length;
    
        // 将日期按从小到大排序
        const sortedTimes = Object.keys(weeklyData).sort((a, b) => new Date(a) - new Date(b));
    
        const xAxisData = [];
        sortedTimes.forEach(time => {
            const scores = weeklyData[time];
            const boxData = calculateBoxPlotData(scores);
            boxPlotData.push(boxData);
            averageData.push(scores.reduce((acc, val) => acc + val, 0) / scores.length);
            xAxisData.push(time);
            allQ1s.push(boxData[1]);  // 收集所有的下四分位值
        });
    
        // 计算下四分位数（Q1）的最小值
        const minQ1 = Math.min(...allQ1s);
    
        const series = [
            {
                name: '成绩箱线图',
                type: 'boxplot',
                data: boxPlotData,
                itemStyle: {
                    color: '#669999',
                    borderColor: '#EE6666',
                    borderWidth: 0
                },
                tooltip: {
                    show: true, // 确保显示tooltip
                    formatter: function (param) {
                        return [
                            `时间: ${param.name}`,
                            `最大值: ${param.data[5]}`,
                            `集中区高点: ${param.data[4]}`,
                            `中位数: ${param.data[3]}`,
                            `集中区低点: ${param.data[2]}`,
                            `最小值: ${param.data[1]}`
                        ].join('<br/>');
                    }
                }
            },
            {
                name: '平均值',
                type: 'line',
                data: averageData,
                lineStyle: {
                    color: '#FFD700', // 亮黄色
                    width: 2,
                    type: 'solid'
                },
                itemStyle: {
                    color: '#FFD700' // 平均值点颜色
                },
                symbol: 'circle',
                symbolSize: 6,
                tooltip: {
                    show: true, // 确保显示tooltip
                    formatter: function (param) {
                        return `时间: ${xAxisData[param.dataIndex]}<br/>平均值: ${param.data}`;
                    }
                }
            },
            {
                // 添加全局平均值的水平线
                name: '全局平均值',
                type: 'line',
                data: Array(xAxisData.length).fill(globalAverage),
                lineStyle: {
                    color: '#FF6347', // 番茄色
                    width: 2,
                    type: 'solid' // 将虚线改为实线
                },
                tooltip: {
                    show: true, // 确保显示tooltip
                    formatter: function () {
                        return `全局平均值: ${globalAverage.toFixed(2)}`;
                    }
                }
            }
        ];
    
        const option = {
            title: {
                text: `${name} 成绩图`,
                left: 'center',
                textStyle: {
                    color: '#ffffff',  // 设置标题颜色为亮白色
                    fontWeight: 'bold',
                    fontSize: 16
                }
            },
            tooltip: {
                trigger: 'item',
                axisPointer: {
                    type: 'cross'
                },
                label: {
                    backgroundColor: '#e5f0ff'
                }
            },
            xAxis: {
                type: 'category',
                data: xAxisData,
                axisLabel: {
                    rotate: 45,
                    fontSize: 8,
                    color: '#ffffff'  // 设置X轴标注颜色为亮白色
                },
                name: '时间   ',
                nameLocation: 'start',
                axisTick: {
                    alignWithLabel: true
                },
                axisLine: {
                    lineStyle: {
                        color: '#ffffff'  // 设置X轴轴线颜色为亮白色
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: '成绩（环值）',
                min: minQ1 - 0.3,  // 动态设置最小值
                max: 10.9,  // 最大值固定为 11
                axisLabel: {
                    formatter: function (value) {
                        return value.toFixed(1); // 保留一位小数
                    },
                    color: '#ffffff'  // 设置Y轴标注颜色为亮白色
                },
                axisLine: {
                    lineStyle: {
                        color: '#ffffff'  // 设置Y轴轴线颜色为亮白色
                    }
                }
            },
            series: series
        };
    
        const chart = echarts.init(chartContainer);
        chart.setOption(option);
    }
    
    
    
    
    function renderComparisonChart(dataList, statsMethod) {
        // 清空图表区域并设置样式
        chartArea.innerHTML = '';
        chartArea.style.display = 'flex';  // 使用flex布局
    
        // 创建图表容器
        const chartContainer = document.createElement('div');
        chartContainer.className = 'chart-container';
        chartArea.appendChild(chartContainer);
    
        const series = [];
        const xAxes = [];
        const grids = [];
        let allQ1s = [];
        const graphics = [];
    
        dataList.forEach((data, index) => {
            const { name, athleteScores } = data;
            const boxPlotData = [];
            const averageData = [];
            const weeklyData = {};
            const allScores = [];  // 用于计算每个人的全局平均值
    
            athleteScores.forEach(score => {
                const time = formatTime(score.datetime, statsMethod);
                if (!weeklyData[time]) {
                    weeklyData[time] = [];
                }
                weeklyData[time].push(...score.socreList);
                allScores.push(...score.socreList);  // 收集所有得分
            });
    
            // 计算每个参与者的全局平均值
            const globalAverage = allScores.reduce((acc, val) => acc + val, 0) / allScores.length;
    
            // 将日期按从小到大排序
            const sortedTimes = Object.keys(weeklyData).sort((a, b) => new Date(a) - new Date(b));
    
            const xAxisData = [];
            sortedTimes.forEach(time => {
                const scores = weeklyData[time];
                const boxData = calculateBoxPlotData(scores);
                boxPlotData.push(boxData);
                averageData.push(scores.reduce((acc, val) => acc + val, 0) / scores.length);
                xAxisData.push(time);
                allQ1s.push(boxData[1]);
            });
    
            // 添加箱线图系列
            series.push({
                name: `${name} 成绩箱线图`,
                type: 'boxplot',
                data: boxPlotData,
                xAxisIndex: index,
                yAxisIndex: index,
                itemStyle: {
                    color: '#669999',
                    borderColor: '#EE6666',
                    borderWidth: 0
                },
                tooltip: {
                    formatter: function (param) {
                        return [
                            `姓名: ${name}`,
                            `时间: ${param.name}`,
                            `最大值: ${param.data[5]}`,
                            `集中区高点: ${param.data[4]}`,
                            `中位数: ${param.data[3]}`,
                            `集中区低点: ${param.data[2]}`,
                            `最小值: ${param.data[1]}`
                        ].join('<br/>');
                    }
                }
            });
    
            // 添加平均值线系列
            series.push({
                name: `${name} 平均值`,
                type: 'line',
                data: averageData,
                xAxisIndex: index,
                yAxisIndex: index,
                lineStyle: {
                    color: '#FFD700', // 亮黄色
                    width: 2,
                    type: 'solid'
                },
                itemStyle: {
                    color: '#FFD700' // 平均值点颜色
                },
                symbol: 'circle',
                symbolSize: 6,
                tooltip: {
                    formatter: function (param) {
                        return `时间: ${xAxisData[param.dataIndex]}<br/>平均值: ${param.data}`;
                    }
                }
            });
    
            // 添加每个参与者的全局平均值水平线
            series.push({
                name: `${name} 全局平均值`,
                type: 'line',
                data: Array(xAxisData.length).fill(globalAverage),
                xAxisIndex: index,
                yAxisIndex: index,
                lineStyle: {
                    color: '#FF6347', // 番茄色
                    width: 2,
                    type: 'solid' // 将虚线改为实线
                },
                tooltip: {
                    formatter: function () {
                        return `全局平均值: ${globalAverage.toFixed(2)}`;
                    }
                }
            });
    
            xAxes.push({
                type: 'category',
                data: xAxisData,
                gridIndex: index,
                axisLabel: {
                    rotate: 45,
                    fontSize: 8,
                    color: '#FFFFFF'  // 修改横坐标标注为亮白色
                },
                name: '时间   ',
                nameLocation: 'start',
                axisTick: {
                    alignWithLabel: true
                },
                axisLine: {
                    lineStyle: {
                        color: '#FFFFFF'  // 修改横坐标线为亮白色
                    }
                }
            });
    
            const chartSpacing = 5; // 每个图表之间的间距（百分比）
            const chartWidth = (100 / dataList.length) - chartSpacing; // 每个图表的宽度（百分比）
            const leftPercentage = index === 0 ? chartSpacing : (chartWidth + chartSpacing) * index + chartSpacing;
    
            grids.push({
                left: `${leftPercentage}%`,
                width: `${chartWidth}%`,
                top: '20%', // 增加 top 值，为名字留出空间
                height: '70%'
            });
    
            graphics.push({
                type: 'text',
                left: `${leftPercentage + chartWidth / 2}%`,
                top: '5%',
                style: {
                    text: name,
                    fill: '#FFFFFF', // 设置名字标注为亮白色
                    font: 'bold 14px sans-serif',
                    textAlign: 'center'
                }
            });
        });
    
        const minQ1 = Math.min(...allQ1s);
    
        const yAxis = dataList.map((data, index) => ({
            type: 'value',
            name: '成绩（环值）',
            gridIndex: index,
            min: minQ1 - 0.3,
            max: 10.9,
            axisLabel: {
                formatter: function (value) {
                    return value.toFixed(1); // 保留一位小数
                },
                color: '#FFFFFF'  // 修改纵坐标标注为亮白色
            },
            axisLine: {
                lineStyle: {
                    color: '#FFFFFF'  // 修改纵坐标线为亮白色
                }
            }
        }));
    
        const option = {
            title: {
                text: '多人成绩对比图',
                left: 'center',
                textStyle: {
                    color: '#e5ffff',  // 设置标题颜色
                    fontWeight: 'bold', // 可选：设置字体粗细
                    fontSize: 16        // 可选：设置字体大小
                }
            },
            tooltip: {
                trigger: 'item',
                axisPointer: {
                    type: 'cross', // 显示交叉的横纵坐标辅助线
                    label: {
                        backgroundColor: '#6a7985' // 辅助线标签背景色
                    }
                },
                formatter: function (params) {
                    const athleteName = params.seriesName.split(' ')[0];
                    return `运动员: ${athleteName}<br/>时间: ${params.name}<br/>成绩: ${params.data}`;
                }
            },
            xAxis: xAxes,
            yAxis: yAxis,
            series: series,
            grid: grids,
            graphic: graphics // 添加graphic组件
        };
    
        const maxContainerWidth = 1000; // 容器最大宽度
        const containerWidth = Math.min(maxContainerWidth, chartArea.offsetWidth); // 动态设置容器宽度
        chartContainer.style.width = `${containerWidth}px`;
    
        const chart = echarts.init(chartContainer);
        chart.setOption(option);
    }
    
    

    // 页面加载时自动选择项目1
    projectSelect.value = '10米气步枪';
    projectSelect.dispatchEvent(new Event('change'));
});
